package beans;


import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import beansInterfaces.UserMgr;
import dto.UserDTO;
import entities.GroupEnum;
import entities.UserEntity;

/**
 * Session Bean implementation class UserMgrBean
 */
@Stateless
public class UserMgrBean implements UserMgr {

	
	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;
	
    /**
     * Default constructor. 
     */
    public UserMgrBean() {
        // TODO Auto-generated constructor stub
    }
    
    public void save(UserDTO user){
    	UserEntity newUser = new UserEntity(user);
		List<GroupEnum> groups = new ArrayList<GroupEnum>();
		groups.add(GroupEnum.USER);
		newUser.setGroup(groups);
		em.persist(newUser);
    };
    
    @RolesAllowed({GroupEnum._USER,GroupEnum._ADMIN})
	public void update(UserDTO user){
		em.merge(new UserEntity(user));
	};
	
	@RolesAllowed({GroupEnum._USER})
	public void unregister(){
		remove(getPrincipalUser());
	}
	
	@RolesAllowed({GroupEnum._USER,GroupEnum._ADMIN})
	public UserDTO getUserDTO(){
		UserDTO userDTO = convertToDTO(getPrincipalUser());
		return userDTO;
	}
	
	public UserEntity find(String username) {
    	return em.find(UserEntity.class, username);
    }
	
	 public void remove(String email) {
			UserEntity user = find(email);
	        em.remove(user);
	}
	
	 public void remove(UserEntity user) {
	    	em.remove(user);
	}
	 
	 public UserEntity getPrincipalUser() {
	    	return find(getPrincipalUsername());
	 }
	 
	 public String getPrincipalUsername() {
	    	return context.getCallerPrincipal().getName();
	 }
	 
	  public UserDTO convertToDTO(UserEntity user) {
			UserDTO userDTO = new UserDTO();
			userDTO.setUsername(user.getUsername());
			userDTO.setFirstName(user.getFirstname());
			userDTO.setLastName(user.getLastname());
			userDTO.setEmail(user.getEmail());
			return userDTO;
		}
}
